﻿using System;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Navigation;
using FirstFloor.Documents.Controls;
using FirstFloor.Documents.IO.DotNetZip;
using FirstFloor.Documents.Presentation.Metadata;

namespace SampleBrowser.Views
{
    public partial class SampleMetadata : Page
    {
        public SampleMetadata()
        {
            InitializeComponent();

            this.Loaded += (o, e) => {
                this.DataSource.PackageReader = new DotNetZipPackageReader(new Uri("Assets/Documents/TestDocument.xps", UriKind.Relative));
            };
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            // properly clears the datasource and closes the package reader
            this.DataSource.PackageReader = null;
        }

        private void DataSource_LoadError(object sender, ErrorEventArgs e)
        {
            new ErrorWindow(e.Error).Show();
        }

        private void DataSource_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Document") {
                if (this.DataSource.Document != null) {
                    // populate tree with metadata nodes
                    var documentNode = new XpsDocumentNode(this.DataSource.Document, "Document Metadata", ViewModelOptions.All);

                    this.TreeView.ItemsSource = new object[] { documentNode };
                }
                else {
                    this.TreeView.ItemsSource = null;
                }
            }
        }

        private void TreeView_SelectedItemChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
        {
            // selects the page associated with the selected node
            var node = e.NewValue as Node;
            if (node != null && node.Page != null) {
                this.Viewer.PageNumber = node.Page.PageNumber;
            }
        }
    }
}
